package com.yuan.fmmall.interceptor;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;

/**
 * @Author Yuan
 * @Date 2021/7/29 21:18
 */
//用于拦截非受限资源，若有token,则重新设置token的过期时间
@Component
public class SetTimeInterceptor implements HandlerInterceptor {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String method = request.getMethod();
        if("OPTIONS".equalsIgnoreCase(method)){
            return true;
        }
        String token = request.getHeader("token");
        if(token!=null){
            String s = stringRedisTemplate.boundValueOps(token).get();
            if(s!=null){
                stringRedisTemplate.boundValueOps(token).expire(30, TimeUnit.MINUTES);
            }
        }
        //此拦截器负责给token延长过期时间（有token且redis中找得到就延长，没有token就不延长），因此无论如何都是返回true
        return true;
    }
}
